
import React, {Component} from 'react';
import {Link} from 'react-router';
import '../work/index.less';
import {connect}from 'react-redux';
import {Table,Icon,Popconfirm,Input,Radio,Button,Spin,Modal,Upload,Form, message} from 'antd';
import {get} from '../../../utils/network';
import {DeleteItem,AddData}from '../../actions/work';
import Nlayer from './nlayer';
import {EditData,AddDatas,SetStatus,EditDatas,GetData,BatchSubmit,SubmitFile}from '../../actions/welcome';
const RadioGroup = Radio.Group;
const FormItem = Form.Item;
import DayPickerInput from 'react-day-picker/DayPickerInput';
import { DateUtils } from "react-day-picker";

class Welcome extends Component {
    constructor(props){
        super(props);
        this.state={
            ...this.props.work,
            ...this.props.welcome,
            uploading: false,
            deituser:{},
            ImportList:[],
            fileList:[],
            dataValue: null,//日期
            dataValue1: null,//止日期
            columns:[{title:'ID',dataIndex:'UserId'},
            {title:'姓名',dataIndex:'UserName'},
            {title:'性别',dataIndex:'UserGender',render:(text,record)=>{
                if(record.UserGender == 0){
                    return <span>男</span>
                }else if(record.UserGender == 1){
                    return <span>女</span>
                }else{
                    return <span>无</span>
                }
            }},
            {title:'手机号',dataIndex:'UserTelPhone'},
            {title:'操作',dataIndex:'',render: (text, record) => {
                return (
                  this.props.work.data.length > 1 ?
                  (
                    <div>
                    <Popconfirm title="Sure to delete?" onConfirm={() => this.onDelete(record.Id)}>
                    <Button type='primary' style={{color:'#fff'}}><a>删除</a></Button>
                    </Popconfirm>
                     <Button type='primary' style={{marginLeft:10}} onClick={()=>this.handleEdit(record)}><a>编辑</a></Button>
                     </div>
                  ) : (<span></span>)
                );
              },}],
              sex:0,
              btnState:0,
              editid:'',
             visible:false,
             btnType:0,
             oldform:{},
        }
    }
    componentWillMount(){
        
    }
    addDay(date,day){
        let t = new Date(date.getFullYear(),date.getMonth(),date.getDate()).getTime()+(day*24000*3600),
            theDay = new Date();
        return new Date(theDay.setTime(t));
    }
    //一年前的昨天
    beforeYear(){
        let yearstr=this.Date(1)
        return new Date(Date.parse(yearstr.replace(/-/g,"/")))
    }
    minDate(){
        let now = new Date(),
            min = this.maxDate();
        return new Date(min.getFullYear()-1,min.getMonth(),min.getDate());
    }
    maxDate(){
        let now = new Date(),
        yestoday = this.addDay(now,-1);
        return new Date(yestoday.getFullYear(),yestoday.getMonth(),yestoday.getDate());
    }
    minDisableDays(){
        var arr = new Array(),
            minDate = this.minDate();
        for(let i=minDate.getDate(); i>0; i--){
            arr.push(new Date(minDate.getFullYear(),minDate.getMonth(),i));
        }
        return arr;
    }
    maxDisableDays(){
        var arr = new Array(),
            maxDate = new Date(),
            nextMonth = new Date(maxDate.getFullYear(),maxDate.getMonth()+1,1),
            lastDayDate = this.addDay(nextMonth,-1);
        for(let i=maxDate.getDate(); i<=lastDayDate.getDate(); i++){
            arr.push(new Date(maxDate.getFullYear(),maxDate.getMonth(),i));
        }
        return arr;
    }
    //日期
    Date(v,n,n1){
        let date=new Date;
        let year=date.getFullYear()-v;
        let day=date.getDate()-v;
        let day1=date.getDate()-1;
        if(n){var month=date.getMonth()-n+1;}else {
            var month=date.getMonth()+1;}
        if(month<10){month="0"+month}
        if(day<10){day="0"+day}
        let h=date.getHours();
        let m=date.getMinutes()
        m=m<10?("0"+m):m
        let yearstr=year+"-"+month+"-"+day+' '+h+":"+m;
        let yearstr1=year+"-"+month+"-"+day;
        let yesterdaygl=year+"-"+month+"-"+day1+' '+h+":"+m;
        let yesterday=year+"-"+month+"-"+day1;
        let beforemonth=year+"-"+month+"-"+day;
        let today=year+"-"+month+"-"+day;
        if(v==0&&n===0&&!n1 ){return yesterday}
        if(v==0&&n===0&&n1=="0" ){return today}
        if(v==0&&!n ){return yesterdaygl}
        if(v==1&&!n1){ return yearstr}
        if(v==1&&n1=="1"){ return yearstr1}
        if(n==3&&v==0){return beforemonth}
    }
   onSelectchange=(selectedRowKeys,selectedRows)=>{
        this.setState({selectedRowKeys:selectedRowKeys});
   }
   handleTableChange=(pagination)=>{
       this.props.dispatch(GetData(pagination));
       pagination.current =pagination.current;
       this.setState({
           pagination:pagination,
       });
   }
   componentDidMount(){
       const pagination={...this.state.pagination};
       pagination.current=1;
       pagination.pageSize=10;
       this.props.dispatch(GetData(pagination));
   }
   onDelete = (key) => {
       this.props.dispatch(DeleteItem(key));
  }
  onChanges=(e)=>{
      this.setState({
          value:e.target.value,
      })
  }
  showModal = () => {
    this.setState({
      visible: true,
      btnType:0,
    });
  }
  handleEdit=(record)=>{
      this.setState({
          btnType:1,
          visible:true,
          deituser:record,
      })
    
  }
  handleOk = (form,type) => {
      if(type == 0){
        this.setState({
            confirmLoading: true,
          });
          this.props.dispatch(AddData(form));
          setTimeout(() => {
            let forms =form;
            forms.id='';
            forms.sex=0;
            forms.username='';
            forms.telephone='';
            this.setState({
             form:forms,
              visible: false,
              confirmLoading: false,
            });
          }, 2000);
      }else{
        this.setState({
            confirmLoading:true,
        });
        console.log(form);
       this.props.dispatch(EditData(form,this.state.deituser.Id));  
       setTimeout(() => {
           let tmp=form;
           tmp.id='';
           tmp.sex=0;
           tmp.username='';
           tmp.telephone='';
            this.setState({
                form:tmp,
                btnType:0,
                edituser:{},
              visible: false,
              confirmLoading: false,
            });
          }, 2000);
        
  }
  }
  handleCancel(){
    this.setState({
      visible: false,
    });
  }
  componentWillReceiveProps(nextProps){
    let newform=nextProps.welcome.form;
    this.setState({
        form:newform
    })

  }
  handleUpload(){
    const { fileList } = this.state;
    const formData = new FormData();
    fileList.forEach((file) => {
      formData.append('files[]', file);
    });
    this.setState({
        uploading: true,
      });
    this.props.dispatch(SubmitFile(formData));
  }
  UploadChange(info){
    if (info.file.status !== 'uploading') {
        console.log('uploading...');//info.file, info.fileList
      }
      if (info.file.status === 'done') {
          const result = info.file.response;
          if(result.State === 1)
          {
              let list = this.state.ImportList;
              let resData = JSON.parse(result.Message);
              list = list.concat(...resData);
              console.log(list);
              this.setState({ImportList:list});
          }
        message.success(`${info.file.name} file uploaded successfully`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} file upload failed.`);
      }
  }
  changeDate(dataValue, date) {
    if (date!=null) {
        if(DateUtils.isSameDay(date,this.state.dataValue) && '1' == dataValue)
            return false;
        if(DateUtils.isSameDay(date,this.state.dataValue1) && '2' == dataValue1)
            return false;
        if(DateUtils.isDayBefore(date,this.minDate())){
            alert("只能查询一年内的,请重新填写");
            date = null
        }
        var now = new Date();
        if(DateUtils.isDayAfter(date,now)){
            alert("只能查询今天以前的,请重新填写");
            date = null  
        }
    }
    if (dataValue == '1') {
        this.setState({
            dataValue: date,
        })
    } else {
        this.setState({
            dataValue1: date,
        })
    }
}
DateInputChange(index,value){
    if(!value) return;
    
    let str = value.split('-');
    if(str.length === 3 && !isNaN(str[0]) && !isNaN(str[1]) && !isNaN(str[2])){
        this.changeDate(index,new Date(str[0],Number(str[1])-1,str[2]));
    }else{
        alert('err');
    }
}
  BatchSubmit(){
    const list  = this.state.ImportList;
    if(list.length > 0){
        this.props.dispatch(BatchSubmit(list));
    }else{
        message.error('还未上传文件');
    }
  }
    render() {
        const { uploading } = this.state;
    const props = {
      action: 'http://101.132.191.91:6011/api/Upload',
      onRemove: (file) => {
        this.setState(({ fileList }) => {
          const index = fileList.indexOf(file);
          const newFileList = fileList.slice();
          newFileList.splice(index, 1);
          return {
            fileList: newFileList,
          };
        });
      },
      beforeUpload: (file) => {
        this.setState(({ fileList }) => ({
          fileList: [...fileList, file],
        }));
        return false;
      },
      fileList: this.state.fileList,
    };

        const {selectedRowKeys}=this.state;
        const rowSelection={
            selections:false,
            onChange:(selectedRowKeys, selectedRows) => {
                console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
            },
            onSelect:(record,selected,selectedRows)=>{
                //console.log(`selectedRows: ${selectedRows}`);
            },
            
            onSelectAll:(record,selected,selectedRows)=>{
                //console.log(`selectedRows: ${selectedRows}`);
            }
        }
        const hasSelected = selectedRowKeys.length > 0;
        const {data,pagination} = this.props.work;
        const DayPickerInputProps = {
            //readOnly:'readonly',
        }
        const start = this.state.dataValue;
        const StartInputProps = {
            ...DayPickerInputProps,
            value:null == start ? "" : `${start.getFullYear()}-${start.getMonth()+1}-${start.getDate()}`,
            onBlur:(v) =>{
                console.log(v.target.value);
                this.DateInputChange('1',v.target.value);
            }
        }
        const end = this.state.dataValue1;
        const EndInputProps = {
            ...DayPickerInputProps,
            value:null == end ? "" : `${end.getFullYear()}-${end.getMonth()+1}-${end.getDate()}`,
            onBlur:(v) =>{
                console.log(v.target.value);
                this.DateInputChange('2',v.target.value);
            }
        }
        const language = {
            locale:"it",
            months:['一月','二月','三月','四月','五月','六月','七月','八月','九月','十月','十一月','十二月'],
            weekdaysLong:['周日','周一','周二','周三','周四','周五','周六'],
            weekdaysShort:['日','一','二','三','四','五','六'],
            disabledDays:[...this.minDisableDays(),...this.maxDisableDays()]
        }
        const StartDayPickerProps = {
            fromMonth:this.minDate(),
            toMonth:this.maxDate(),
            ...language
        }
        const EndDayPickerProps = {
            fromMonth:this.state.dataValue,
            toMonth:this.maxDate(),
            ...language
        }
        return (
            <div>
            <div>
                <Link to='/work'>欢迎进入我的练习页面</Link>
            </div>
            <div style={{margin:50}}>
                <Form>
                    <FormItem>
                        <DayPickerInput
                            inputProps={StartInputProps}
                            dayPickerProps={StartDayPickerProps}
                            onDayChange={(date,modifiers) =>{
                                // if(undefined !== date){
                                //     this.changeDate('1',date);
                                // }else{
                                //     alert('error');
                                // }
                            }}
                            placeholder="开始日期"
                        />
                    </FormItem>
                    <FormItem>
                        <DayPickerInput
                            inputProps={EndInputProps}
                            dayPickerProps={EndDayPickerProps}
                            onDayChange={(date,modifiers) =>{
                                // if(undefined !== date){
                                //     this.changeDate('2',date);
                                // }
                            }}
                            placeholder="结束日期"
                        />
                    </FormItem>
                </Form>
            </div>
            

            <div>
                <Upload {...props}>
                <Button>
                    <Icon type="upload" /> Select File
                </Button>
                </Upload>
                <Button
                className="upload-demo-start"
                type="primary"
                onClick={this.handleUpload.bind(this)}
                disabled={this.state.fileList.length === 0}
                loading={uploading}
                >
                {uploading ? 'Uploading' : 'Start Upload' }
                </Button>
            </div>
            <Button type='primary' className='newplus' onClick={this.BatchSubmit.bind(this)}>批量添加</Button>
            <Button type='primary' className='newplus' onClick={this.showModal.bind(this)}>新增</Button>
            <Nlayer ref='layers' showstate={this.state.btnType} edituser={this.state.deituser} visible={this.state.visible} handleOk={this.handleOk.bind(this)} handleCancel={()=>this.handleCancel()}/>
            <div id='content' style={{ marginBottom: 16 }}>
               <Table 
               rowSelection={rowSelection} 
               columns={this.state.columns} 
               dataSource={data} 
               rowKey={record=>record.Id}
               pagination={pagination}
               onChange={this.handleTableChange}
               />
             </div>
             {this.props.work.loading?(<Spin className='position' size='large' tip='loading...'/>):(<span/>)}
            </div>  
        )
    }
}
const mapStateToProps=(state)=>{
    return {
        work:state.work,
        welcome:state.welcome,
    }
}
export default connect(mapStateToProps)(Welcome);